// pages/signup/signup.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    username: '',
    password: '',
    showPassword: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 页面加载时的初始化逻辑
    console.log('登录页面已加载');
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  onUsernameInput(e) {
    this.setData({ username: e.detail.value });
  },

  onPasswordInput(e) {
    this.setData({ password: e.detail.value });
  },

  onTogglePassword() {
    this.setData({ showPassword: !this.data.showPassword });
  },

  // 模拟用户数据
  mockUsers: [
    { username: 'admin', password: '123456', role: 'admin' },
    { username: 'user', password: 'password', role: 'user' },
    { username: 'test', password: 'test123', role: 'user' },
    { username: 'demo', password: 'demo123', role: 'demo' }
  ],

  // 本地登录验证
  localLogin(username, password) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        const user = this.mockUsers.find(u => 
          u.username === username && u.password === password
        );
        
        if (user) {
          resolve({
            success: true,
            user: {
              username: user.username,
              role: user.role
            },
            message: '登录成功'
          });
        } else {
          reject({
            success: false,
            message: '用户名或密码错误'
          });
        }
      }, 1000); // 模拟1秒网络延迟
    });
  },

  // 保存登录状态
  saveLoginState(userInfo) {
    wx.setStorageSync('isLoggedIn', true);
    wx.setStorageSync('currentUser', userInfo);
    wx.setStorageSync('loginTime', Date.now());
    // 同步userInfo给myselfMessage页面
    wx.setStorageSync('userInfo', {
      avatar: '/pages/demo3/imge/gengar.png', // 可根据需要自定义
      name: userInfo.username,
      gender: '不详',
      region: '******',
      phone: '**********',
    });
  },

  // 检查登录状态
  checkLoginState() {
    const isLoggedIn = wx.getStorageSync('isLoggedIn');
    const loginTime = wx.getStorageSync('loginTime');
    
    // 检查登录是否过期（24小时）
    if (isLoggedIn && loginTime) {
      const now = Date.now();
      const expireTime = 24 * 60 * 60 * 1000; // 24小时
      if (now - loginTime > expireTime) {
        this.clearLoginState();
        return false;
      }
    }
    
    return isLoggedIn;
  },

  // 清除登录状态
  clearLoginState() {
    wx.removeStorageSync('isLoggedIn');
    wx.removeStorageSync('currentUser');
    wx.removeStorageSync('loginTime');
  },

  onLogin() {
    const { username, password } = this.data;
    
    // 输入验证
    if (!username || !password) {
      wx.showToast({ title: '请输入用户名和密码', icon: 'none' });
      return;
    }

    // 显示加载提示
    wx.showLoading({ title: '登录中...' });

    // 使用本地验证登录
    this.localLogin(username, password)
      .then(result => {
        wx.hideLoading();
        
        // 保存登录状态
        this.saveLoginState({
          ...result.user,
          avatar: '/pages/demo3/imge/gengar.png', // 可根据注册时选择头像扩展
        });
        
        // 显示成功提示
        wx.showToast({ 
          title: result.message, 
          icon: 'success',
          duration: 1500
        });
        
        // 登录成功后直接跳转到"我的"页面
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/demo3/demo3',
            success: () => {
              console.log('跳转到我的页面成功');
            },
            fail: (error) => {
              console.error('跳转到我的页面失败:', error);
              wx.showToast({ 
                title: '跳转失败，请重试', 
                icon: 'none' 
              });
            }
          });
        }, 1500);
      })
      .catch(error => {
        wx.hideLoading();
        wx.showToast({ 
          title: error.message, 
          icon: 'none',
          duration: 2000
        });
      });
  },

  // 快速登录功能（用于测试）
  onQuickLogin() {
    wx.showActionSheet({
      itemList: ['admin/123456', 'user/password', 'test/test123', 'demo/demo123'],
      success: (res) => {
        const testUsers = [
          { username: 'admin', password: '123456' },
          { username: 'user', password: 'password' },
          { username: 'test', password: 'test123' },
          { username: 'demo', password: 'demo123' }
        ];
        
        const selectedUser = testUsers[res.tapIndex];
        this.setData({
          username: selectedUser.username,
          password: selectedUser.password
        });
        wx.showToast({ 
          title: `已选择: ${selectedUser.username}`, 
          icon: 'success' 
        });
        // 直接自动登录并跳转
        wx.showLoading({ title: '登录中...' });
        this.localLogin(selectedUser.username, selectedUser.password)
          .then(result => {
            wx.hideLoading();
            this.saveLoginState(result.user);
            wx.showToast({ 
              title: result.message, 
              icon: 'success',
              duration: 1500
            });
            setTimeout(() => {
              // 跳转到demo3页面
              wx.switchTab({
                url: '/pages/demo3/demo3',
                success: () => {
                  console.log('快速登录跳转成功');
                },
                fail: (error) => {
                  console.error('跳转失败:', error);
                  wx.showToast({ 
                    title: '跳转失败，请重试', 
                    icon: 'none' 
                  });
                }
              });
            }, 1500);
          })
          .catch(error => {
            wx.hideLoading();
            wx.showToast({ 
              title: error.message, 
              icon: 'none',
              duration: 2000
            });
          });
      }
    });
  }
})